package com.zfb.videoscript.core

import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.util.Log
import androidx.core.content.FileProvider
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.io.File

class UpdateManager(private val context: Context) {
    private var downloadId: Long = 0
    private val logManager = LogManager(context)
    
    private val _updateProgress = MutableStateFlow(0)
    val updateProgress: StateFlow<Int> = _updateProgress
    
    private val downloadReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == DownloadManager.ACTION_DOWNLOAD_COMPLETE) {
                val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
                if (id == downloadId) {
                    installApk()
                }
            }
        }
    }
    
    init {
        context.registerReceiver(
            downloadReceiver,
            IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
        )
    }
    
    fun checkUpdate(currentVersion: String, onNewVersion: (String, String) -> Unit) {
        // TODO: 实现检查更新逻辑
        // 这里模拟发现新版本
        val newVersion = "1.2.0"
        val updateInfo = "1. 新增自动更新功能\n2. 优化用户体验\n3. 修复已知问题"
        if (newVersion > currentVersion) {
            onNewVersion(newVersion, updateInfo)
        }
    }
    
    fun downloadUpdate(url: String) {
        try {
            val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
            
            val apkName = "zfb_video_new.apk"
            val apkFile = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), apkName)
            if (apkFile.exists()) {
                apkFile.delete()
            }
            
            val request = DownloadManager.Request(Uri.parse(url)).apply {
                setTitle("正在下载更新")
                setDescription("ZFB刷视频更新包")
                setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, apkName)
            }
            
            downloadId = downloadManager.enqueue(request)
            logManager.logOperation("开始下载", "开始下载新版本")
            
            // 监控下载进度
            Thread {
                var isDownloading = true
                while (isDownloading) {
                    val query = DownloadManager.Query().setFilterById(downloadId)
                    val cursor = downloadManager.query(query)
                    if (cursor.moveToFirst()) {
                        val downloadedBytes = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
                        val totalBytes = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
                        if (totalBytes > 0) {
                            val progress = ((downloadedBytes * 100) / totalBytes).toInt()
                            _updateProgress.value = progress
                        }
                        
                        val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))
                        if (status == DownloadManager.STATUS_SUCCESSFUL || status == DownloadManager.STATUS_FAILED) {
                            isDownloading = false
                        }
                    }
                    cursor.close()
                    Thread.sleep(500)
                }
            }.start()
            
        } catch (e: Exception) {
            Log.e("UpdateManager", "下载更新失败", e)
            logManager.logOperation("下载失败", e.message ?: "未知错误")
        }
    }
    
    private fun installApk() {
        try {
            val apkFile = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "zfb_video_new.apk")
            if (!apkFile.exists()) {
                logManager.logOperation("安装失败", "更新包不存在")
                return
            }
            
            val intent = Intent(Intent.ACTION_VIEW)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                val uri = FileProvider.getUriForFile(
                    context,
                    "${context.packageName}.fileprovider",
                    apkFile
                )
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                intent.setDataAndType(uri, "application/vnd.android.package-archive")
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive")
            }
            
            context.startActivity(intent)
            logManager.logOperation("开始安装", "启动安装界面")
            
        } catch (e: Exception) {
            Log.e("UpdateManager", "安装更新失败", e)
            logManager.logOperation("安装失败", e.message ?: "未知错误")
        }
    }
    
    fun onDestroy() {
        try {
            context.unregisterReceiver(downloadReceiver)
        } catch (e: Exception) {
            Log.e("UpdateManager", "注销广播接收器失败", e)
        }
    }
} 